import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Toast } from 'antd-mobile';
import axios from 'axios';
import { getUserInfo } from '../utils/auth';
import { http, host, port } from '../utils/host'
import { LeftOutline } from 'antd-mobile-icons'

// 定义接口
interface User {
  _id: string;
  userId: string;
  username: string;
  avatarImage?: string;
  school?: string;
  followersCount: number;
  followingCount: number;
  dongtaiCount: number;
  // 根据实际数据结构添加其他字段
}

interface Dongtai {
  _id: string;
  content: string;
  images?: string[];
  likeCount: number;
  commentCount: number;
  publishTime: string;
  // 根据实际数据结构添加其他字段
}

const UserDetail: React.FC = () => {
  const { userId } = useParams<{ userId: string }>();
  const navigate = useNavigate();
  const [userInfo, setUserInfo] = useState<User | null>(null);
  const [dongtaiList, setDongtaiList] = useState<Dongtai[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [isFollowing, setIsFollowing] = useState<boolean>(false);
  // 添加关注操作的加载状态
  const [isLoading, setIsLoading] = useState<boolean>(false);

  // 获取当前用户信息
  useEffect(() => {
    const user = getUserInfo<User | null>();
    setCurrentUser(user);
  }, []);

  // 获取用户详情
  const fetchUserDetail = async (): Promise<void> => {
    try {
      const response = await axios.get(`${http}${host}${port}/dongtai/getUserDetail?userId=${userId}`);
      setUserInfo(response.data);
      fetchUserDongtai();
      checkFollowingStatus();
    } catch (error) {
      console.error('获取用户详情失败:', error);
      Toast.show({ content: '获取用户详情失败', type: 'fail', position: 'center' });
    } finally {
      setLoading(false);
    }
  };

  // 获取用户动态
  const fetchUserDongtai = async (): Promise<void> => {
    try {
      const response = await axios.get(`${http}${host}${port}/dongtai/getUserDongtai?userId=${userId}`);
      setDongtaiList(response.data);
    } catch (error) {
      console.error('获取用户动态失败:', error);
    }
  };

  // 检查关注状态
  const checkFollowingStatus = async (): Promise<void> => {
    // 如果没有当前用户或目标用户ID，默认设置为未关注
    if (!currentUser || !userId) {
      setIsFollowing(false);
      return;
    }

    try {
      const response = await axios.get(`${http}${host}${port}/dongtai/checkFollowing?followerId=${currentUser.userId}&followedId=${userId}`);
      setIsFollowing(response.data.isFollowing);
    } catch (error) {
      console.error('检查关注状态失败:', error);
      Toast.show({ content: '检查关注状态失败', type: 'fail', position: 'center' });
      // 错误情况下默认设置为未关注
      setIsFollowing(false);
    }
  };

  // 关注/取消关注用户
  const handleFollow = async (): Promise<void> => {
    // 添加防止重复点击的检查
    if (isLoading) return;

    if (!currentUser) {
      Toast.show({ content: '请先登录', type: 'fail', position: 'center' });
      return;
    }

    if (currentUser.userId === userId) {
      Toast.show({ content: '不能关注自己', type: 'fail', position: 'center' });
      return;
    }

    // 设置加载状态
    setIsLoading(true);

    try {
      const response = await axios.post(`${http}${host}${port}/dongtai/follow`, {
        followerId: currentUser.userId,
        followedId: userId,
        follow: !isFollowing
      });

      // 更新关注状态
      setIsFollowing(!isFollowing);
      // 更新关注数
      setUserInfo(prev => ({
        ...prev,
        followersCount: response.data.followersCount
      }));

      Toast.show({ content: isFollowing ? '已取消关注' : '关注成功', type: 'success', position: 'center' });
    } catch (error) {
      console.error('关注操作失败:', error);
      // 更具体的错误提示
      const errorMessage = error.response?.data?.message || '操作失败，请重试';
      Toast.show({ content: errorMessage, type: 'fail', position: 'center' });
    } finally {
      // 无论成功失败，都要清除加载状态
      setIsLoading(false);
    }
  };

  // 格式化时间差
  const formatTimeDifference = (publishTime: string): string => {
    if (!publishTime) return '';

    const now = new Date();
    const publishDate = new Date(publishTime);
    const diffInSeconds = Math.floor((now - publishDate) / 1000);

    const secondsInMinute = 60;
    const secondsInHour = secondsInMinute * 60;
    const secondsInDay = secondsInHour * 24;
    const secondsInMonth = secondsInDay * 30;
    const secondsInYear = secondsInDay * 365;

    if (diffInSeconds < secondsInMinute) {
      return `${diffInSeconds}秒前`;
    } else if (diffInSeconds < secondsInHour) {
      return `${Math.floor(diffInSeconds / secondsInMinute)}分钟前`;
    } else if (diffInSeconds < secondsInDay) {
      return `${Math.floor(diffInSeconds / secondsInHour)}小时前`;
    } else if (diffInSeconds < secondsInMonth) {
      return `${Math.floor(diffInSeconds / secondsInDay)}天前`;
    } else if (diffInSeconds < secondsInYear) {
      return `${Math.floor(diffInSeconds / secondsInMonth)}个月前`;
    } else {
      return `${Math.floor(diffInSeconds / secondsInYear)}年前`;
    }
  };

  useEffect(() => {
    fetchUserDetail();
  }, [userId]);

  if (loading) {
    return (
      <div style={styles.loadingContainer}>
        <div style={styles.spinner}></div>
        <p style={styles.loadingText}>加载中...</p>
      </div>
    );
  }

  if (!userInfo) {
    return (
      <div style={styles.errorContainer}>
        <p style={styles.errorText}>用户不存在</p>
      </div>
    );
  }
  return (
    <div style={styles.container}>
      {/* 顶部导航 */}
      <div style={styles.header}>
        <div style={styles.backIcon} onClick={() => navigate(-1)}><LeftOutline /></div>
        <div style={styles.title}>用户详情</div>
        <div style={styles.placeholder}></div>
      </div>

      {/* 用户信息头部 */}
      <div style={styles.userHeader}>
        <img
          src={userInfo.avatarImage || 'default-avatar.png'}
          alt={userInfo.username}
          style={styles.avatar}
          onError={(e) => {
            // 如果本地存储的头像加载失败，回退到默认头像
            (e.target as HTMLImageElement).src = "";
          }}
        />
        <div style={styles.userInfo}>
          <div style={styles.username}>{userInfo.username || userInfo._id}</div>
          <div style={styles.schoolInfo}>{userInfo.school || ''}</div>
        </div>
        <button
          style={{
            ...styles.followButton,
            backgroundColor: isFollowing ? '#F0F0F0' : '#FF6B6B',
            color: isFollowing ? '#333' : '#FFF',
            opacity: isLoading ? 0.7 : 1,
            cursor: isLoading ? 'not-allowed' : 'pointer'
          }}
          onClick={handleFollow}
          disabled={isLoading}
        >
          {isLoading ? '处理中...' : (isFollowing ? '已关注' : '关注')}
        </button>
      </div>

      {/* 数据统计 */}
      <div style={styles.statsContainer}>
        <div style={styles.statItem}>
          <div style={styles.statValue}>{userInfo.dongtaiCount || 0}</div>
          <div style={styles.statLabel}>动态</div>
        </div>
        <div style={styles.statItem}>
          <div style={styles.statValue}>{userInfo.followersCount || 0}</div>
          <div style={styles.statLabel}>粉丝</div>
        </div>
        <div style={styles.statItem}>
          <div style={styles.statValue}>{userInfo.followingCount || 0}</div>
          <div style={styles.statLabel}>关注</div>
        </div>
      </div>

      {/* 简介 */}
      {userInfo.bio && (
        <div style={styles.bioContainer}>
          <p style={styles.bioText}>{userInfo.bio}</p>
        </div>
      )}

      {/* 动态列表 */}
      <div style={styles.dongtaiListContainer}>
        <h2 style={styles.dongtaiListTitle}>动态 ({dongtaiList.length})</h2>
        {dongtaiList.length > 0 ? (
          <div style={styles.dongtaiList}>
            {dongtaiList.map((item) => (
              <div key={item._id} style={styles.dongtaiItem} onClick={() => navigate(`/dongtai-detail/${item._id}`)}>
                <div style={styles.dongtaiHeader}>
                  <img
                    src={userInfo.avatarImage || 'default-avatar.png'}
                    alt={userInfo.username}
                    style={styles.dongtaiAvatar}
                    onError={(e) => {
                      // 如果本地存储的头像加载失败，回退到默认头像
                      (e.target as HTMLImageElement).src = "";
                    }}
                  />
                  <div style={styles.dongtaiUserInfo}>
                    <div style={styles.dongtaiUsername}>{userInfo.username || userInfo._id}</div>
                    <div style={styles.dongtaiPublishTime}>{formatTimeDifference(item.createdAt)}</div>
                  </div>
                </div>
                <div style={styles.dongtaiContent}>{item.title}</div>
                {item.media && item.media.length > 0 && (
                  <div style={styles.mediaContainer}>
                    {item.media.map((url, index) => {
                      const isVideo = url.match(/\.(mp4|mov|webm|avi|mkv)$/i);
                      const mediaUrl = `${http}${host}${port}` + url;

                      if (isVideo) {
                        return (
                          <video
                            key={index}
                            src={mediaUrl}
                            alt=""
                            style={styles.mediaVideo}
                            loop
                            muted
                            playsInline
                          />
                        );
                      } else {
                        return (
                          <img
                            key={index}
                            src={mediaUrl}
                            alt=""
                            style={styles.mediaImage}
                          />
                        );
                      }
                    })}
                  </div>
                )}
                <div style={styles.dongtaiFooter}>
                  <div style={styles.publishTime}></div>
                  <div style={styles.interactionBar}>
                    <span style={styles.interactionIcon}>👍 {item.likeCount || 0}</span>
                    <span style={styles.interactionIcon}>💬 {item.commentCount || 0}</span>
                    <span style={styles.interactionIcon}>🔄 {item.shareCount || 0}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div style={styles.emptyState}>
            <p style={styles.emptyText}>暂无动态</p>
          </div>
        )}
      </div>
    </div>
  );
};

const styles = {
  container: {
    width: '100%',
    maxWidth: '100%',
    fontFamily: 'Arial, sans-serif',
    backgroundColor: '#FFFFFF',
    height: '100%',
    minHeight: '100vh',
    overflowX: 'hidden',
    overflowY: 'auto', // 启用垂直滚动
  },
  header: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '15px 16px',
    backgroundColor: '#FFFFFF',
    boxShadow: '0 1px 0 rgba(0,0,0,0.1)',
    position: 'sticky',
    top: 0,
    zIndex: 100,
  },
  backIcon: {
    fontSize: '20px',
    color: '#333',
    cursor: 'pointer',
  },
  title: {
    fontSize: '18px',
    fontWeight: 'bold',
    color: '#333',
  },
  placeholder: {
    width: '20px',
  },
  loadingContainer: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    height: '100vh',
  },
  spinner: {
    width: '40px',
    height: '40px',
    border: '4px solid #f3f3f3',
    borderTop: '4px solid #3498db',
    borderRadius: '50%',
    animation: 'spin 1s linear infinite',
    marginBottom: '16px',
  },
  loadingText: {
    fontSize: '16px',
    color: '#999',
  },
  errorContainer: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    height: '100vh',
  },
  errorText: {
    fontSize: '18px',
    color: '#FF6B6B',
  },
  userHeader: {
    display: 'flex',
    alignItems: 'center',
    padding: '24px 16px',
    borderBottom: '1px solid #F0F0F0',
  },
  avatar: {
    width: '80px',
    height: '80px',
    borderRadius: '50%',
    objectFit: 'cover',
    marginRight: '16px',
    border: '2px solid #F0F0F0',
  },
  userInfo: {
    flex: 1,
  },
  username: {
    fontSize: '18px',
    fontWeight: 'bold',
    color: '#333',
    marginBottom: '4px',
  },
  schoolInfo: {
    fontSize: '14px',
    color: '#999',
  },
  followButton: {
    padding: '6px 16px',
    borderRadius: '20px',
    border: 'none',
    fontSize: '14px',
    fontWeight: 'bold',
    cursor: 'pointer',
  },
  statsContainer: {
    display: 'flex',
    justifyContent: 'space-around',
    padding: '20px 0',
    borderBottom: '1px solid #F0F0F0',
  },
  statItem: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  statValue: {
    fontSize: '20px',
    fontWeight: 'bold',
    color: '#333',
  },
  statLabel: {
    fontSize: '14px',
    color: '#999',
    marginTop: '4px',
  },
  bioContainer: {
    padding: '16px',
    borderBottom: '1px solid #F0F0F0',
  },
  bioText: {
    fontSize: '16px',
    color: '#333',
    lineHeight: '1.5',
  },
  dongtaiListContainer: {
    padding: '16px',
  },
  dongtaiListTitle: {
    fontSize: '18px',
    fontWeight: 'bold',
    color: '#333',
    marginBottom: '16px',
  },
  dongtaiList: {
    width: '100%',
  },
  dongtaiItem: {
    backgroundColor: '#FFFFFF',
    borderRadius: '12px',
    padding: '16px',
    marginBottom: '16px',
    boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
    cursor: 'pointer',
  },
  dongtaiHeader: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: '12px',
  },
  dongtaiAvatar: {
    width: '40px',
    height: '40px',
    borderRadius: '50%',
    objectFit: 'cover',
    marginRight: '12px',
  },
  dongtaiUserInfo: {
    display: 'flex',
    flexDirection: 'column',
  },
  dongtaiUsername: {
    fontSize: '14px',
    fontWeight: 'bold',
    color: '#333',
  },
  dongtaiPublishTime: {
    fontSize: '12px',
    color: '#999',
  },
  dongtaiContent: {
    fontSize: '16px',
    color: '#333',
    marginBottom: '12px',
    lineHeight: '1.5',
  },
  mediaContainer: {
    display: 'flex',
    flexWrap: 'wrap',
    gap: '8px',
    marginBottom: '12px',
  },
  mediaImage: {
    width: '48%',
    height: 'auto',
    borderRadius: '8px',
    objectFit: 'cover',
  },
  mediaVideo: {
    width: '100%',
    height: 'auto',
    borderRadius: '8px',
    backgroundColor: '#000',
    maxHeight: '200px',
  },
  dongtaiFooter: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: '12px',
  },
  publishTime: {
    fontSize: '12px',
    color: '#999',
  },
  interactionBar: {
    display: 'flex',
    gap: '16px',
  },
  interactionIcon: {
    fontSize: '14px',
    color: '#999',
  },
  emptyState: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    padding: '40px 0',
  },
  emptyText: {
    fontSize: '16px',
    color: '#999',
  },
};

// 添加CSS动画
const styleSheet = document.createElement('style');
styleSheet.textContent = `
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
`;
document.head.appendChild(styleSheet);

export default UserDetail;